<template>
  <div class="statistics">
    <div class="page-header">
      <h2>商品销售统计</h2>
    </div>

    <el-card class="search-card">
      <div class="search-form">
        <div class="date-picker">
          <span class="label">日期范围:</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateChange">
          </el-date-picker>
        </div>
        <div class="product-select">
          <span class="label">商品选择:</span>
          <el-select
            v-model="selectedProduct"
            placeholder="选择商品"
            clearable
            @change="handleProductChange">
            <el-option
              v-for="product in products"
              :key="product.productId"
              :label="product.name"
              :value="product.productId">
            </el-option>
          </el-select>
        </div>
        <el-button type="primary" @click="searchStats">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </el-card>

    <el-card class="box-card" v-loading="loading">
      <div class="chart-container">
        <div id="sales-chart" ref="salesChart" class="chart"></div>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>销售明细</span>
      </div>
      <el-table
        :data="stats"
        border
        style="width: 100%">
        <el-table-column
          prop="date"
          label="日期"
          min-width="120">
          <template slot-scope="scope">
            {{ formatDate(scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column
          label="商品名称"
          min-width="180">
          <template slot-scope="scope">
            {{ scope.row.product ? scope.row.product.name : '未知商品' }}
          </template>
        </el-table-column>
        <el-table-column
          label="商品分类"
          min-width="120">
          <template slot-scope="scope">
            {{ scope.row.product ? scope.row.product.category : '未知分类' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="salesCount"
          label="销售数量"
          width="120">
        </el-table-column>
        <el-table-column
          prop="revenue"
          label="销售金额"
          width="120">
          <template slot-scope="scope">
            {{ scope.row.revenue }} 元
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination">
      </el-pagination>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>销售统计汇总</span>
      </div>
      <div class="summary-container">
        <div class="summary-item">
          <div class="summary-title">销售总量</div>
          <div class="summary-value">{{ totalSales }}</div>
        </div>
        <div class="summary-item">
          <div class="summary-title">销售总额</div>
          <div class="summary-value">{{ totalRevenue.toFixed(2) }} 元</div>
        </div>
        <div class="summary-item">
          <div class="summary-title">商品种类</div>
          <div class="summary-value">{{ productCount }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import statApi from '@/api/stat'
import productApi from '@/api/product'
import moment from 'moment'
import * as echarts from 'echarts'

export default {
  name: 'Statistics',

  data() {
    return {
      loading: true,
      stats: [],
      allStats: [],
      products: [],
      dateRange: [
        moment().subtract(30, 'days').format('YYYY-MM-DD'),
        moment().format('YYYY-MM-DD')
      ],
      selectedProduct: '',
      salesChart: null,
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },

  computed: {
    // 计算总销售量
    totalSales() {
      return this.allStats.reduce((sum, item) => sum + item.salesCount, 0)
    },

    // 计算总销售额
    totalRevenue() {
      return this.allStats.reduce((sum, item) => sum + parseFloat(item.revenue), 0)
    },

    // 计算商品种类数
    productCount() {
      const productIds = new Set(this.allStats.map(item => item.productId))
      return productIds.size
    }
  },

  created() {
    this.fetchProducts()
    this.fetchDefaultStats()
  },

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },

  methods: {
    // 获取产品列表
    async fetchProducts() {
      try {
        const response = await productApi.getAllProducts()
        this.products = response.data
      } catch (error) {
        this.$message.error('获取商品列表失败')
      }
    },

    // 获取默认统计数据（过去30天）
    async fetchDefaultStats() {
      this.loading = true
      
      // 设置默认时间范围为过去30天
      const endDate = moment().format('YYYY-MM-DD')
      const startDate = moment().subtract(30, 'days').format('YYYY-MM-DD')
      this.dateRange = [startDate, endDate]
      
      try {
        console.log(`获取统计数据: ${startDate} 至 ${endDate}`)
        const response = await statApi.getStatsByDateRange(startDate, endDate)
        console.log('统计数据响应:', response)
        
        if (response.data) {
          this.allStats = response.data
          this.filterStats()
          if (this.salesChart) {
            this.updateChart()
          }
        } else {
          console.error('获取到的统计数据为空')
          this.allStats = []
        }
        this.loading = false
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error(`获取统计数据失败: ${error.message || '未知错误'}`)
        this.loading = false
        this.allStats = []
      }
    },

    // 根据日期范围获取统计数据
    async fetchStatsByDateRange(startDate, endDate) {
      this.loading = true
      try {
        const response = await statApi.getStatsByDateRange(startDate, endDate)
        this.allStats = response.data
        this.filterStats()
        this.updateChart()
        this.loading = false
      } catch (error) {
        this.$message.error('获取统计数据失败')
        this.loading = false
      }
    },

    // 根据产品ID获取统计数据
    async fetchStatsByProduct(productId) {
      this.loading = true
      try {
        const response = await statApi.getStatsByProduct(productId)
        this.allStats = response.data
        this.filterStats()
        this.updateChart()
        this.loading = false
      } catch (error) {
        this.$message.error('获取统计数据失败')
        this.loading = false
      }
    },

    // 初始化图表
    initChart() {
      try {
        console.log('初始化图表...')
        if (this.salesChart) {
          this.salesChart.dispose()
          this.salesChart = null
        }
        
        const chartDom = this.$refs.salesChart
        if (!chartDom) {
          console.error('找不到图表DOM元素 (使用$refs)')
          const domById = document.getElementById('sales-chart')
          if (!domById) {
            console.error('找不到图表DOM元素 (使用getElementById)')
            return
          }
          this.salesChart = echarts.init(domById)
        } else {
          this.salesChart = echarts.init(chartDom)
        }
        
        this.salesChart.setOption({
          title: {
            text: '商品销售统计'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: []
          },
          yAxis: [
            {
              type: 'value',
              name: '销售数量'
            },
            {
              type: 'value',
              name: '销售金额'
            }
          ],
          series: []
        })
        
        console.log('图表初始化成功')
        if (this.allStats && this.allStats.length > 0) {
          this.updateChart()
        }
      } catch (error) {
        console.error('图表初始化错误:', error)
      }
    },

    // 更新图表数据
    updateChart() {
      if (!this.salesChart) {
        console.warn('图表实例不存在，尝试重新初始化')
        this.initChart()
        if (!this.salesChart) {
          console.error('图表初始化失败')
          return
        }
      }

      try {
        if (!this.allStats || this.allStats.length === 0) {
          this.salesChart.setOption({
            title: {
              text: '暂无数据'
            },
            xAxis: {
              data: []
            },
            series: []
          })
          return
        }

        const sortedStats = [...this.allStats].sort((a, b) => {
          return new Date(a.date) - new Date(b.date)
        })

        const dates = sortedStats.map(item => this.formatDate(item.date))
        const salesCounts = sortedStats.map(item => item.salesCount)
        const revenues = sortedStats.map(item => parseFloat(item.revenue))

        console.log('更新图表数据:', { dates, salesCounts, revenues })

        this.salesChart.setOption({
          title: {
            text: '商品销售统计'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['销售数量', '销售金额']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: dates
          },
          yAxis: [
            {
              type: 'value',
              name: '销售数量',
              position: 'left'
            },
            {
              type: 'value',
              name: '销售金额',
              position: 'right',
              axisLabel: {
                formatter: '{value} 元'
              }
            }
          ],
          series: [
            {
              name: '销售数量',
              type: 'bar',
              data: salesCounts
            },
            {
              name: '销售金额',
              type: 'line',
              yAxisIndex: 1,
              data: revenues
            }
          ]
        })
      } catch (error) {
        console.error('更新图表错误:', error)
      }

      window.addEventListener('resize', this.resizeChart)
    },

    // 重绘图表
    resizeChart() {
      this.salesChart && this.salesChart.resize()
    },

    // 过滤统计数据
    filterStats() {
      let filtered = [...this.allStats]

      if (this.selectedProduct) {
        filtered = filtered.filter(item => item.productId === this.selectedProduct)
      }

      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = new Date(this.dateRange[0])
        const endDate = new Date(this.dateRange[1])

        filtered = filtered.filter(item => {
          const itemDate = new Date(item.date)
          return itemDate >= startDate && itemDate <= endDate
        })
      }

      this.total = filtered.length

      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.stats = filtered.slice(start, end)
    },

    // 搜索统计数据
    searchStats() {
      if (this.dateRange && this.dateRange.length === 2) {
        const startDate = this.dateRange[0]
        const endDate = this.dateRange[1]

        if (this.selectedProduct) {
          this.fetchStatsByDateRange(startDate, endDate)
        } else {
          this.fetchStatsByDateRange(startDate, endDate)
        }
      } else if (this.selectedProduct) {
        this.fetchStatsByProduct(this.selectedProduct)
      } else {
        this.fetchDefaultStats()
      }
    },

    // 重置搜索
    resetSearch() {
      this.dateRange = [
        moment().subtract(30, 'days').format('YYYY-MM-DD'),
        moment().format('YYYY-MM-DD')
      ]
      this.selectedProduct = ''
      this.fetchDefaultStats()
    },

    // 处理日期变化
    handleDateChange() {
      this.currentPage = 1
    },

    // 处理商品变化
    handleProductChange() {
      this.currentPage = 1
    },

    // 格式化日期
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD')
    },

    // 页面大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.filterStats()
    },

    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.filterStats()
    }
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart)

    if (this.salesChart) {
      this.salesChart.dispose()
      this.salesChart = null
    }
  }
}
</script>

<style scoped>
.statistics {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.date-picker, .product-select {
  display: flex;
  align-items: center;
}

.label {
  margin-right: 10px;
  white-space: nowrap;
}

.chart-container {
  height: 400px;
  width: 100%;
}

#sales-chart {
  height: 100%;
  width: 100%;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.summary-container {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.summary-item {
  text-align: center;
  padding: 20px;
  border-radius: 4px;
  background-color: #f8f9fa;
  min-width: 200px;
}

.summary-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
</style>
